import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:provider_lab/simple/simple_model.dart';

class SimpleHomePage extends StatelessWidget {
  const SimpleHomePage({Key key}) : super(key: key);

  Future<SimpleModel> delayCreateModel() async {
    await Future.delayed(Duration(seconds: 3));
    return SimpleModel();
  }

  @override
  // Widget build(BuildContext context) => _changeNotifierProviderExp();
  Widget build(BuildContext context) => _futureProviderExp();

  Widget _changeNotifierProviderExp() {
    return ChangeNotifierProvider(
      // 直接创建
      create: (_) => SimpleModel(),
      child: _buildChild(),
    );
  }

  Widget _futureProviderExp() {
    return FutureProvider(
      // 异步创建
      create: (context) async {
        await Future.delayed(Duration(seconds: 3));
        return SimpleModel();
      },
      child: _buildChild(),
    );
  }

  Widget _buildChild() {
    return Scaffold(
      appBar: AppBar(
        title: Text('provider'),
      ),
      body: Column(
        children: <Widget>[
          Builder(
            builder: (context) {
              // 获得 provider 提供的值
              SimpleModel _model = Provider.of<SimpleModel>(context);
              return Container(
                  margin: const EdgeInsets.only(top: 20),
                  width: MediaQuery.of(context).size.width,
                  padding: const EdgeInsets.all(20),
                  alignment: Alignment.center,
                  color: Colors.lightBlueAccent,
                  child: Text('当前是：${_model.counter}'));
            },
          ),
          Consumer<SimpleModel>(
            builder: (context, model, child) {
              return Container(
                margin: const EdgeInsets.only(top: 20),
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.all(20),
                alignment: Alignment.center,
                color: Colors.lightGreen,
                child: Text(
                  '${model.counter}',
                ),
              );
            },
          ),
          Consumer<SimpleModel>(
            builder: (context, model, child) {
              return FlatButton(
                  color: Colors.tealAccent,
                  onPressed: model.incrementCounter,
                  child: Icon(Icons.add));
            },
          ),
        ],
      ),
    );
  }
}
